<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package      925CMS
 * @subpackage  Categories
 * @category      Module
 * @author      Phil Sturgeon - 925CMS Dev Team
 */

class Admin_Categories extends Admin_Controller
{
    /**
     * Array that contains the validation rules
     * @access protected
     * @var array
     */
    protected $validation_rules;

    /**
     * The constructor
     * @access public

     * @return \Admin_Categories
     */
    public function __construct()
    {

        parent::__construct();
        $this->load->model('blog_categories_m');
        $this->lang->load('categories');
        $this->lang->load('blog');
        $this->template->set_partial('shortcuts', 'admin/partials/shortcuts');
        $this->template->append_metadata(js('categories.js', 'blog'));
        $this->template->append_metadata(css('categories.css', 'blog'));

        // Set the validation rules
        $this->validation_rules = array(
            array(
                'field' => 'title',
                'label' => lang('categories.title_label'),
                'rules' => 'trim|required|max_length[20]|callback__check_title'
            ),
        );

        // Load the validation library along with the rules
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->validation_rules);
    }

    /**
     * Index method, lists all categories
     * @access public
     * @return void
     */
    public function index()
    {

        $this->pyrocache->delete_all('modules_m');

        // Create pagination links
        $total_rows = $this->blog_categories_m->count_all();
        $pagination = create_pagination('admin/blog/categories/index', $total_rows);

        // Using this data, get the relevant results
        $categories = $this->blog_categories_m->get_category_tree();
        $this->data->controller = & $this;
        $this->template->title($this->module_details['name'], lang('cat_list_title'))
                ->set('categories', $categories)
                ->set('pagination', $pagination)
                ->append_metadata(js('jquery/jquery.ui.nestedSortable.js'))
                ->append_metadata(js('jquery/jquery.cooki.js'))
                ->build('admin/categories/index', $this->data);
    }

    /**
     * Create method, creates a new category
     * @access public
     * @return void
     */
    public function create()
    {
        // Validate the data
        if ($this->form_validation->run()) {

            if ($this->blog_categories_m->insert($_POST)) {
                $this->session->set_flashdata('success', sprintf(lang('cat_add_success'), $this->input->post('title')));

                // echo success to let the js refresh the page
                echo 'success';
                return;
            } else {
                $this->session->set_flashdata(array(
                                                   'error' => lang('cat_add_error')
                                              ));
                echo $this->load->view('admin/partials/notices', $this->data);
                return;
            }
        }

        // check for errors

        if (validation_errors()) {
            echo $this->load->view('admin/partials/notices', $this->data);
            return;
        }

        // Loop through each validation rule
        foreach ($this->validation_rules as $rule) {
            /** @var $category string */
            $category->{$rule['field']} = set_value($rule['field']);
        }

        // Render the view
        $this->data->category = & $category;
        $this->load->view('admin/categories/form', $this->data);
    }

    /**
     * Edit method, edits an existing category
     * @access public
     * @param int $id The ID of the category to edit
     * @return void
     */
    public function edit($id = 0)
    {


        // Get the category
        $category = $this->blog_categories_m->get($id);

        // ID specified?
        $category or redirect('admin/blog/categories/index');

        // Validate the results

        if ($this->form_validation->run()) {
            if ($this->blog_categories_m->update($id, $_POST)) {
                $this->session->set_flashdata('success', sprintf(lang('cat_edit_success'), $this->input->post('title')));

                // echo success to let the js refresh the page
                echo 'success';
                return;
            } else {
                $this->session->set_flashdata(array(
                                                   'error' => lang('cat_edit_error')
                                              ));
                echo $this->load->view('admin/partials/notices', $this->data);
                return;
            }
        }
        // check for errors

        if (validation_errors()) {
            echo $this->load->view('admin/partials/notices', $this->data);
            return;
        }
        // Loop through each rule
        foreach ($this->validation_rules as $rule) {

            if ($this->input->post($rule['field']) !== FALSE) {
                $category->{$rule['field']} = $this->input->post($rule['field']);
            }
        }
        // Render the view
        $this->data->category = & $category;
        $this->load->view('admin/categories/form', $this->data);
    }

    /**
     * Order the links and record their children
     *
     * @access public
     * @return string json message
     */
    public function order()
    {

        $order = $this->input->post('order');

        if (is_array($order)) {

            //reset all parent > child relations
            $this->blog_categories_m->update_cat_by(array(
                                                         'parent' => 0
                                                    ));
            foreach ($order as $i => $link) {

                //set the order of the root links
                $this->blog_categories_m->update_by('id', str_replace('category_', '', $link['id']), array(
                                                                                                          'position' => $i
                                                                                                     ));

                //iterate through children and set their order and parent
                $this->blog_categories_m->_set_children($link);
            }
            $this->pyrocache->delete_all('blog_categories_m');
            echo 'Success';
        } else {
            echo 'Fail';
        }
    }


    /**
     * Delete method, deletes an existing category (obvious isn't it?)
     * @access public
     * @param int $id The ID of the category to edit
     * @return void
     */
    public function delete($id = 0)
    {

        $id_array = (!empty($id)) ? array(
            $id
        ) : $this->input->post('action_to');

        // Delete multiple

        if (!empty($id_array)) {
            if ($this->blog_categories_m->delete($id)) {
                $this->session->set_flashdata('success', $this->lang->line('cat_delete_success'));
            } else {
                $this->session->set_flashdata('error', $this->lang->line('cat_delete_error'));
            }
        } else {
            $this->session->set_flashdata('error', $this->lang->line('cat_no_select_error'));
        }
        redirect('admin/blog/categories/index');
    }

    /**
     * Callback method that checks the title of the category
     * @access public
     * @param string title The title to check
     * @return bool
     */
    public function _check_title($title = '')
    {


        if ($this->blog_categories_m->check_title($title)) {
            $this->form_validation->set_message('_check_title', sprintf($this->lang->line('cat_already_exist_error'), $title));
            return FALSE;
        }
        return TRUE;
    }

    /**
     * Create method, creates a new category via ajax
     * @access public
     * @return void
     */
    public function create_ajax()
    {


        // Loop through each validation rule
        foreach ($this->validation_rules as $rule) {
            /** @var $category string */
            $category->{$rule['field']} = set_value($rule['field']);
        }
        $this->data->method = 'create';
        $this->data->category = & $category;

        if ($this->form_validation->run()) {
            $id = $this->blog_categories_m->insert_ajax($_POST);

            if ($id > 0) {
                $message = sprintf(lang('cat_add_success'), $this->input->post('title'));
            } else {
                $message = lang('cat_add_error');
            }
            return $this->template->build_json(array(
                                                    'message' => $message,
                                                    'title' => $this->input->post('title'),
                                                    'category_id' => $id,
                                                    'status' => 'ok'
                                               ));
        } else {

            // Render the view
            $form = $this->load->view('admin/categories/form', $this->data, TRUE);

            if ($errors = validation_errors()) {
                return $this->template->build_json(array(
                                                        'message' => $errors,
                                                        'status' => 'error',
                                                        'form' => $form
                                                   ));
            }
            echo $form;
        }
    }
}
